import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'
import React, { useEffect, useState } from 'react'
import './styles/base.css'
import './styles/index.css'
export const Context = React.createContext()
const { Provider } = Context
const Todos = () => {
  const [list, setList] = useState(() => {
    return JSON.parse(localStorage.getItem('toods')) || []
  })
  const [type, setType] = useState('all')
  useEffect(() => {
    localStorage.setItem('toods', JSON.stringify(list))
  }, [list])
  // 添加任务
  const addTodo = (name) => {
    setList([
      {
        id: Date.now(),
        name,
        done: false,
      },
      ...list,
    ])
  }
  // 删除任务
  const delTodo = (id) => {
    setList(list.filter((item) => item.id !== id))
  }
  // 修改任务状态
  const chengeDone = (id) => {
    setList(
      list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            done: !item.done,
          }
        } else {
          return item
        }
      })
    )
  }
  // 更新数据
  const upadteTodo = ({ id, name }) => {
    console.log(id, name)
    setList(
      list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            name,
          }
        } else {
          return item
        }
      })
    )
  }
  return {
    list,
    type,
    delTodo,
    chengeDone,
    upadteTodo,
    setType,
    addTodo,
  }
}
const App = () => {
  const { list, type, delTodo, chengeDone, upadteTodo, setType, addTodo } =
    Todos()
  return (
    <Provider value={{ delTodo, chengeDone, upadteTodo }}>
      <section className="todoapp">
        <TodoHeader addTodo={addTodo} />
        <TodoMain list={list} type={type} />
        <TodoFooter list={list} type={type} setType={setType} />
      </section>
    </Provider>
  )
}

export default App
